package cn.cjj.gulimall.order.service.impl;

import cn.cjj.common.to.OrderEntityTo;
import cn.cjj.common.utils.R;
import cn.cjj.common.vo.MemberResponseVo;
import cn.cjj.gulimall.order.constant.OrderConstant;
import cn.cjj.gulimall.order.entity.OrderItemEntity;
import cn.cjj.gulimall.order.enume.OrderStatusEnum;
import cn.cjj.gulimall.order.feign.CartFeignService;
import cn.cjj.gulimall.order.feign.MemberFeignService;
import cn.cjj.gulimall.order.feign.ProductFeignService;
import cn.cjj.gulimall.order.feign.WareFeignService;
import cn.cjj.gulimall.order.interceptor.LoginUserInterceptor;
import cn.cjj.gulimall.order.service.OrderItemService;
import cn.cjj.gulimall.order.to.OrderCreateTo;
import cn.cjj.gulimall.order.vo.*;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import org.aspectj.weaver.ast.Or;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureOrder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.cjj.common.utils.PageUtils;
import cn.cjj.common.utils.Query;

import cn.cjj.gulimall.order.dao.OrderDao;
import cn.cjj.gulimall.order.entity.OrderEntity;
import cn.cjj.gulimall.order.service.OrderService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;


@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {

    @Autowired
    MemberFeignService memberFeignService;

    @Autowired
    CartFeignService cartFeignService;

    @Autowired
    ThreadPoolExecutor executor;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    WareFeignService wareFeignService;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    OrderService orderService;

    @Autowired
    OrderItemService orderItemService;

    @Autowired
    RabbitTemplate rabbitTemplate;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public OrderConfirmVo confirmOrder() throws ExecutionException, InterruptedException {
        MemberResponseVo user = LoginUserInterceptor.threadLocal.get();

        OrderConfirmVo orderConfirm = new OrderConfirmVo();


        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();

        CompletableFuture<Void> addressTask = CompletableFuture.runAsync(() -> {
            RequestContextHolder.setRequestAttributes(requestAttributes);
            List<MemberAddressVo> address = memberFeignService.getAddress(user.getId());
            orderConfirm.setAddress(address);
        }, executor);

        CompletableFuture<Void> cartItemsTask = CompletableFuture.runAsync(() -> {
            RequestContextHolder.setRequestAttributes(requestAttributes);
            List<OrderItemVo> orderItems = cartFeignService.currentUserCartItems();
            orderConfirm.setItems(orderItems);
        }, executor);


        Integer integration = user.getIntegration();
        orderConfirm.setIntegration(integration);

        String token = UUID.randomUUID().toString().replace("-", "");
        redisTemplate.opsForValue().set(OrderConstant.USER_ORDER_TOKEN_PREFIX + user.getId(), token, 30, TimeUnit.MINUTES);
        orderConfirm.setOrderToken(token);

        CompletableFuture.allOf(addressTask, cartItemsTask).get();

        return orderConfirm;
    }

    @Transactional
    @Override
    public SubmitOrderResponseVo submitOrder(OrderSubmitVo order) {
        MemberResponseVo user = LoginUserInterceptor.threadLocal.get();

        SubmitOrderResponseVo resp = new SubmitOrderResponseVo();

        String orderToken = order.getOrderToken();
        String script =
                "if redis.call('get', KEYS[1]) == ARGV[1] " +
                "then return redis.call('del', KEYS[1]) " +
                "else return 0 end";
        Long r = redisTemplate.execute(
                new DefaultRedisScript<>(script, Long.class),
                Arrays.asList(OrderConstant.USER_ORDER_TOKEN_PREFIX + user.getId()),
                orderToken);

        if (r == 0L) {
            resp.setCode(1);
            return resp;
        }

        OrderCreateTo orderCreate = createOrder(order);

//        if (Math.abs(orderCreate.getPayPrice().subtract(order.getPayPrice()).doubleValue()) >= 0.01) {
//            resp.setCode(2);
//            return resp;
//        }


        R lockResp = lockOrderItemStock(orderCreate);
        if (lockResp.getCode() != 0) {
            resp.setCode(3);
            return resp;
        }

        saveOrder(orderCreate);

        if (orderCreate.getOrderItems().size() == 2) {
            int a = 10 / 0;
        }

        rabbitTemplate.convertAndSend("order-event-exchange", "order.create.order", orderCreate.getOrder());


        resp.setCode(0);
        resp.setOrderEntity(orderCreate.getOrder());
        return resp;
    }

    @Override
    public int getOrderStatus(String orderSn) {
        OrderEntity orderEntity = getOne(new QueryWrapper<OrderEntity>().eq("order_sn", orderSn));
        if (orderEntity == null) {
            return -1;
        }

        return orderEntity.getStatus();
    }

    @Override
    public void closeOrder(OrderEntity order) {
        OrderEntity order2 = this.getById(order.getId());
        if (order2.getStatus().equals(OrderStatusEnum.CREATE_NEW.getCode())) {
            OrderEntity orderEntity = new OrderEntity();
            orderEntity.setId(order.getId());
            orderEntity.setStatus(OrderStatusEnum.CANCLED.getCode());
            this.updateById(orderEntity);

            OrderEntityTo orderEntityTo = new OrderEntityTo();
            BeanUtils.copyProperties(order2, orderEntityTo);

            rabbitTemplate.convertAndSend("order-event-exchange", "order.release.other", orderEntityTo);
        }
    }

    private R lockOrderItemStock(OrderCreateTo orderCreate) {
        List<OrderItemVo> lockItems = orderCreate.getOrderItems().stream().map(orderItem -> {
            OrderItemVo item = new OrderItemVo();
            item.setSkuId(orderItem.getSkuId());
            item.setCount(orderItem.getSkuQuantity());
            item.setTitle(orderItem.getSkuName());

            return item;
        }).collect(Collectors.toList());

        WareSkuLockVo wareSkuLock = new WareSkuLockVo();
        wareSkuLock.setOrderSn(orderCreate.getOrder().getOrderSn());
        wareSkuLock.setLocks(lockItems);

        return wareFeignService.orderLockStock(wareSkuLock);
    }

    private void saveOrder(OrderCreateTo orderCreate) {
        OrderEntity order = orderCreate.getOrder();
        order.setModifyTime(new Date());
        orderService.save(order);

        List<OrderItemEntity> orderItems = orderCreate.getOrderItems();
        orderItemService.saveBatch(orderItems);
    }

    private OrderCreateTo createOrder(OrderSubmitVo order) {
        MemberResponseVo user = LoginUserInterceptor.threadLocal.get();

        OrderCreateTo orderCreateTo = new OrderCreateTo();

        String orderSn = IdWorker.getTimeId();

        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSn(orderSn);
        orderEntity.setMemberId(user.getId());

        List<OrderItemVo> orderItemVos = cartFeignService.currentUserCartItems();
        if (orderItemVos != null && orderItemVos.size() > 0) {
            List<OrderItemEntity> orderItems = orderItemVos.stream().map(orderItemVo -> {
                OrderItemEntity orderItem = new OrderItemEntity();
                orderItem.setOrderSn(orderSn);

                orderItem.setSkuId(orderItemVo.getSkuId());
                orderItem.setSkuName(orderItemVo.getTitle());
                orderItem.setSkuPic(orderItemVo.getImage());
                orderItem.setSkuQuantity(orderItemVo.getCount());
                String attrs = StringUtils.collectionToDelimitedString(orderItemVo.getSkuAttr(), ";");
                orderItem.setSkuAttrsVals(attrs);

                orderItem.setGiftGrowth(orderItemVo.getPrice().intValue());
                orderItem.setGiftIntegration(orderItemVo.getPrice().intValue());

                SpuInfoVo spuInfo = productFeignService.getSpuInfoBySkuId(orderItemVo.getSkuId());
                orderItem.setSpuId(spuInfo.getId());
                orderItem.setSpuBrand(spuInfo.getBrandId().toString());
                orderItem.setSpuName(spuInfo.getSpuName());
                orderItem.setCategoryId(spuInfo.getCatalogId());

                orderItem.setSkuPrice(orderItemVo.getPrice());
                orderItem.setSkuQuantity(orderItemVo.getCount());
                orderItem.setPromotionAmount(new BigDecimal("0.0"));
                orderItem.setCouponAmount(new BigDecimal("0.0"));
                orderItem.setIntegrationAmount(new BigDecimal("0.0"));
                BigDecimal total = orderItem.getSkuPrice().multiply(new BigDecimal(orderItem.getSkuQuantity().toString()));
                total = total.subtract(orderItem.getPromotionAmount())
                        .subtract(orderItem.getCouponAmount())
                        .subtract(orderItem.getIntegrationAmount());
                orderItem.setRealAmount(total);

                return orderItem;
            }).collect(Collectors.toList());
            orderCreateTo.setOrderItems(orderItems);
        }

        FareVo fare = wareFeignService.getFare(order.getAddrId());
        orderEntity.setFreightAmount(fare.getFare());
        orderEntity.setReceiverDetailAddress(fare.getAddress().getDetailAddress());
        orderEntity.setReceiverName(fare.getAddress().getName());
        orderEntity.setReceiverPhone(fare.getAddress().getPhone());
        orderEntity.setReceiverPostCode(fare.getAddress().getPostCode());
        orderEntity.setReceiverProvince(fare.getAddress().getProvince());
        orderEntity.setReceiverRegion(fare.getAddress().getRegion());

        BigDecimal total = new BigDecimal("0.0");
        BigDecimal coupon = new BigDecimal("0.0");
        BigDecimal integration = new BigDecimal("0.0");
        BigDecimal promotion = new BigDecimal("0.0");
        Integer giftGrowth = 0;
        Integer giftIntegration = 0;
        for (OrderItemEntity orderItem : orderCreateTo.getOrderItems()) {
            total = total.add(orderItem.getRealAmount());
            coupon = coupon.add(orderItem.getCouponAmount());
            integration = integration.add(orderItem.getIntegrationAmount());
            promotion = promotion.add(orderItem.getPromotionAmount());
            giftGrowth = giftGrowth + orderItem.getGiftGrowth();
            giftIntegration = giftIntegration + orderItem.getGiftIntegration();
        }
        orderEntity.setTotalAmount(total);
        orderEntity.setCouponAmount(coupon);
        orderEntity.setIntegration(integration.intValue());
        orderEntity.setPromotionAmount(promotion);
        orderEntity.setPayAmount(total.add(orderEntity.getFreightAmount()));
        orderEntity.setGrowth(giftGrowth);
        orderEntity.setIntegration(giftIntegration);

        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        orderEntity.setAutoConfirmDay(7);

        orderCreateTo.setPayPrice(total);
        orderCreateTo.setOrder(orderEntity);

        return orderCreateTo;
    }
}